package executor

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"xiaoniu-job/internal/db"
	"xiaoniu-job/pkg"
)

// 执行器新增 更新 删除

func AddHandler(w http.ResponseWriter, r *http.Request) {
	res, err := ioutil.ReadAll(r.Body)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("参数有误"))
	}
	var entity pkg.Executor
	err = json.Unmarshal(res, &entity)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("JSON转换异常"))
	}
	cnt, err := db.AddExecutor(&entity)
	if cnt > 0 {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("新增执行器成功"))
	} else {
		w.WriteHeader(http.StatusBadRequest)
		var errMsg string
		if err != nil {
			errMsg = err.Error()
		}
		w.Write([]byte("新增执行器失败，错误信息为:" + errMsg))
	}
}

func UpdateHandler(w http.ResponseWriter, r *http.Request) {
	res, err := ioutil.ReadAll(r.Body)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("参数有误"))
		return
	}
	var entity pkg.Executor
	err = json.Unmarshal(res, &entity)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("JSON转换异常"))
		return
	}
	cnt, err := db.UpdateExecutor(&entity)
	if cnt > 0 {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("更新执行器成功"))
	} else {
		w.WriteHeader(http.StatusBadRequest)
		var errMsg string
		if err != nil {
			errMsg = err.Error()
		}
		w.Write([]byte("更新执行器失败，错误信息为:" + errMsg))
	}
}

func DeleteHandler(w http.ResponseWriter, r *http.Request) {
	res, err := ioutil.ReadAll(r.Body)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("参数有误"))
		return
	}
	var entity pkg.Executor
	err = json.Unmarshal(res, &entity)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("JSON转换异常"))
		return
	}
	cnt, err := db.DeleteExecutor(entity.Id)
	if cnt > 0 {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("删除执行器成功"))
	} else {
		w.WriteHeader(http.StatusBadRequest)
		var errMsg string
		if err != nil {
			errMsg = err.Error()
		}
		w.Write([]byte("删除执行器失败，错误信息为:" + errMsg))
	}
}

func ListHandler(w http.ResponseWriter, r *http.Request) {
	res, err := ioutil.ReadAll(r.Body)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("参数有误"))
		return
	}
	var entity pkg.ExecutorSearch
	err = json.Unmarshal(res, &entity)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("JSON转换异常"))
		return
	}
	marshal, err := json.Marshal(db.GetExecutorList(&entity))
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("响应转换异常"))
		return
	}
	w.Write(marshal)

}

func SelectHandler(w http.ResponseWriter, r *http.Request) {
	marshal, err := json.Marshal(db.GetExecutorMapForSelect())
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("响应转换异常"))
		return
	}
	w.Write(marshal)

}
